package com.example.demo.mapper;


import com.example.demo.entity.ChatMessage;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ChatMessageMapper {
    // 插入一条消息
    @Insert("INSERT INTO chat_message(sender_id, receiver_id, content, send_time, is_read) " +
            "VALUES(#{senderId}, #{receiverId}, #{content}, #{sendTime}, #{isRead})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertMessage(ChatMessage chatMessage);

    // 根据ID查询消息
    @Select("SELECT * FROM chat_message WHERE id = #{id}")
    ChatMessage selectMessageById(Long id);

    // 查询两个用户之间的聊天记录
    @Select("SELECT * FROM chat_message " +
            "WHERE (sender_id = #{userId1} AND receiver_id = #{userId2}) OR " +
            "(sender_id = #{userId2} AND receiver_id = #{userId1}) " +
            "ORDER BY send_time ASC")
    List<ChatMessage> selectChatHistory(@Param("userId1") Long userId1, @Param("userId2") Long userId2);

    // 将消息标记为已读
// 在ChatMessageMapper.java中添加
    @Update("UPDATE chat_message SET is_read = 1 WHERE id = #{id}")
    void markAsRead(@Param("id") Long id);

    // 获取用户未读消息数量
    @Select("SELECT COUNT(*) FROM chat_message WHERE receiver_id = #{userId} AND is_read = 0")
    int getUnreadCount(Long userId);
}